package conteoller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/*
 * @Description：
 *       用来记录servlet公共部分
 * @Author: JiangFan
 * @Date: 2019/3/7
 * @Time：10:58
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet (HttpServletRequest req, HttpServletResponse resp)
            throws  IOException {
       this.doPost (req,resp);
    }

    @Override
    protected void doPost (HttpServletRequest req, HttpServletResponse resp)
            throws  IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        // 获取请求标识,（执行方法名）
        String methodName = req.getParameter("op");
        // 默认方法
        if (methodName == null) {
            methodName = "execute";
        }
        System.out.println("BaseServlet : " + this + " , " + methodName);
        try {
            // 2、通过反射获得当前运行类中指定方法,形式参数
            Method executeMethod = this.getClass().getMethod (methodName,
                                                              HttpServletRequest.class,
                                                              HttpServletResponse.class);
            // 3、反射执行方法
            String result = (String)executeMethod.invoke(this,req,resp);
            // 4、将json数据返回
            resp.getWriter().write(result);
            /*// 获取指定类的字节码对象
            // 这里的this指的是继承BaseServlet对象
            Class<? extends BaseServlet> clazz = this.getClass();

            // 通过类的字节码对象获取方法的字节码对象
            Method method = clazz.getMethod (methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 让方法执行
            method.invoke(this, req, resp);*/
        }catch (NoSuchMethodException e) {
            throw new RuntimeException("请求的方法[" + methodName + "]不存在");
        } catch (Exception e) {
            throw new RuntimeException ("服务器异常",e);
        }
    }

    /**
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void execute(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
    }
}
